using UnityEngine;

public class FreeLookCamera : MonoBehaviour
{
    // 鼠标灵敏度
    public float sensitivity = 2.0f;

    // 垂直旋转限制
    public float maxVerticalAngle = 80f;

    // 平滑旋转的速度
    public float rotationDamping = 5.0f;

    // 摄像机的初始旋转角度
    private float xRotation = 0f;

    // 是否锁定鼠标光标
    private bool cursorLocked = true;

    // 用于旋转的辅助 Transform
    private Transform rotationTransform;

    // 摄像机的原始视野
    private float originalFov;

    // 摄像机的当前视野
    private float fov;

    private void Start()
    {
        // 创建一个辅助 Transform 用于旋转
        rotationTransform = new GameObject("RotationHelper").transform;
        rotationTransform.position = transform.position;

        // 锁定鼠标光标
        LockCursor();

        // 设置摄像机的原始视野
        originalFov = Camera.main.fieldOfView;
        fov = originalFov;
    }

    private void LateUpdate()
    {
        // 旋转摄像机
        if (cursorLocked)
        {
            float mouseX = Input.GetAxis("Mouse X") * sensitivity;
            float mouseY = Input.GetAxis("Mouse Y") * sensitivity;

            // 更新水平旋转
            rotationTransform.Rotate(Vector3.up * mouseX);

            // 更新垂直旋转
            xRotation -= mouseY;
            xRotation = Mathf.Clamp(xRotation, -maxVerticalAngle, maxVerticalAngle);

            // 平滑旋转
            Quaternion targetRotation = Quaternion.Euler(xRotation, rotationTransform.eulerAngles.y, 0f);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * rotationDamping);
        }

        // 检测是否按下 ESC 键来切换鼠标锁定状态
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            ToggleCursorLock();
        }

        // 检测鼠标右键状态以调整视野
        if (Input.GetMouseButtonDown(1)) // 鼠标右键按下
        {
            fov = originalFov * .2f;
        }
        else if (Input.GetMouseButtonUp(1)) // 鼠标右键松开
        {
            fov = originalFov;
        }

        // 平滑调整视野
        Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, fov, Time.deltaTime * 5f);
    }

    private void LockCursor()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
        cursorLocked = true;
    }

    private void UnlockCursor()
    {
        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
        cursorLocked = false;
    }

    private void ToggleCursorLock()
    {
        if (cursorLocked)
        {
            UnlockCursor();
        }
        else
        {
            LockCursor();
        }
    }
}